<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\form\api\controller;

use onekey\Email;
use think\facade\View;
use think\facade\Validate;
use app\api\BaseController;
use app\api\model\User;
use app\api\model\UserGroup;
use plugins\form\api\addons\TencentLocationService;
use plugins\form\api\model\Set;
use plugins\form\api\model\Message;
use plugins\form\api\validate\Submit;
use think\exception\ValidateException;
/**
 * 表单模块
 */
class Form extends BaseController
{
    /**
     * 提交
     */
    public function submit()
    {
        if ($this->request->isPost()) {
            try{
                $input = input('post.');
                $set = Set::where('id', $input['id'])->where('status', 1)->find();
                if (empty($set)) {
                    return json(['status' => 'error', 'message' => '表单不存在']);
                }
                // 验证码
                if ($set['captcha'] == 1) {
                    if (empty($input['code'])) {
                        return json(["status" => "error", "message" => '请填写验证码']);
                    }
                    if (! password_verify($input['code'], $input['rcode'])) {
                        return json(["status" => "error", "message" => '验证码错误']);
                    }
                }
                // 验证内容
                foreach ($set['field'] as $key => $val) {
                    if (empty($input['content'][$val['field']]) && $val['request']) {
                        return json(['status' => 'error', 'message' => $val['field'] . '不能为空']);
                    }
                }
                // 验证权限
                if (! empty($set['group_id'])) {
                    if (empty($this->request->userId)) {
                        return json(['status' => 'error','message' => '留言提交权限不足']);
                    }
                    $history_integral = User::where('id', $this->request->userId)->value('history_integral');
                    $group_id = UserGroup::where('integral', '<=', $history_integral)->order('integral', 'desc')->value('id');
                    if (! in_array($group_id, $data->group_id)) {
                        return json(['status' => 'error','message' => '留言提交权限不足']);
                    }
                }
                // 验证信息
                validate(Submit::class)->check($input);
                // 时间间隔
                if (! empty($set['interval'])) {
                    $LastSubmittedData = Message::where('ip', request()->ip())->where('form_id', $input['id'])->order('create_time', 'desc')->value('create_time');
                    if ($LastSubmittedData) {
                        if ((time() - strtotime($LastSubmittedData)) < $set['interval']) {
                            return json(['status' => 'error', 'message' => '提交间隔不能小于'. $set['interval'] . '秒']);
                        }
                    }
                }
                $tencent  = new TencentLocationService();
                $location = $tencent->ipLocation();
                $array['ip']       = request()->ip();
                $array['country']  = $location['nation'];
                $array['province'] = $location['province'];
                $array['city']     = $location['city'];
        		$save = Message::create([
                    'form_id'     => $input['id'],
                    'user_id'     => $this->request->userId ? $this->request->userd : 0,
                    'content'     => $input['content'],
                    'ip'          => $array['ip'],
                    'country'     => $array['country'],
                    'province'    => $array['province'],
                    'city'        => $array['city'],
                    'read'        => 0,
                    'create_time' => date('Y-m-d H:i:s'),
                ]);
                // 发送邮件
                if (! empty($set['email'])) {
                    $title = '客户留言通知';
                    $body  = '';
                    $body .= "本邮件为OneKeyAdmin系统发送，请不要直接回复！<br/>";
                    $body .= "请点击客户邮箱进行回复！<br/>";
                    $body .= "--------------------------------------------------------------------<br/>";
                    foreach ($save['content'] as $key => $value) {
                        $body .= "".$key."：".$value."<br/>";
                    }
                    $body .= "--------------------------------------------------------------------<br/>";
                    $body .= "留言IP ：".$save['ip']."<br/>";
                    $body .= "所在地区：".$save['country'].$save['province'].$save['city']."<br/>";
                    $body .= "--------------------------------------------------------------------<br/>";
                    $res  = Email::send($set['email'], $title, $body);
                    if ($res['status'] === 'error') {
                        return json($res);
                    }
                }
                return json(['status' => 'success', 'message' => '提交成功']);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
        }
    }
}